<?php

namespace App\Http\Controllers\Backstage;

use App\Banner;
use App\Doctors;
use App\EveryDayLoginRecord;
use App\FeaturesMenu;
use App\Http\Services\FileManager;
use App\IntegralChildRule;
use App\IntegralRule;
use App\PayRule;
use App\Services\UserManager;
use App\UserInfo;
use App\VerifyPhone;
use App\VipInfo;
use App\VipRule;
use Illuminate\Http\Request;
use Blocktrail\CryptoJSAES\CryptoJSAES;

use App\User;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use App\Permission;
use App\Role;
use DB;
use Hash;
use Auth;
use Cookie;
use phpDocumentor\Reflection\DocBlock;

class AdminController extends Controller
{
    /**
     * 后台登录操作
     * @param Request $request
     * @return $this|\Illuminate\Http\JsonResponse
     */
    public function signInUser(Request $request){
        $username = $request->get('username');
        $password = $request->get('password');

        /** @var User $isUser */
        $isUser = User::whereUsername($username)->first();
        if(!$isUser)
            return response()->json(['level' => 'error','message' => '该用户不存在']);

        /** @var User $user */
        $user = UserManager::signInByUsername($username,$password,0);
        if(!$user)
            return response()->json(['level'=>'error','message'=>'帐号或密码错误！']);

//        if(!$user->can('admin_sign_in') && !$user->can('system_admin'))
//            return response()->json(['level' => 'error','message' => '没有登录权限','data'=>'no_permission']);

        if($user->status != 1)
            return response()->json(['level' => 'error','message' => '该账号已被锁定']);

        $userMark = $user->user_key;

        $token = CryptoJSAES::encrypt($userMark,env('AES_KEY'));

        $cookie = Cookie::forever("user_token", $token);

        return response()->json(['level' => 'success','message' => trans("登录成功！"),'data' => $token])->withCookie($cookie);
    }

    public function signInDoctor(Request $request){
        $phone = $request->get('phone');
        $verifyPhone = $request->get('verify_phone');

        if(!preg_match("/^(1[34578])[0-9]{9}$/", trim($phone)))
            return response()->json(['level' => 'error','message' => '请正确输入手机号码！']);

        /** @var VerifyPhone $verifyCodeByPhone */
        $verifyCodeByPhone=VerifyPhone::wherePhone(trim($phone))->whereVerifyCode(trim($verifyPhone))->first();
        if(!$verifyCodeByPhone || strtotime($verifyCodeByPhone->created_at) + 60 * 15 < time()){
            return response()->json(['level'=>'error','message' => '验证码不匹配或已过期']);
        }

        $verifyCodeByPhone -> delete();

        /** @var Doctors $thisDoctor */
        $thisDoctor = Doctors::wherePhone($phone)->first();
        if(!$thisDoctor)
            return response()->json(['level' => 'error','message' => '医生信息不存在']);

        /** @var UserInfo $thisUserInfo */
        $thisUserInfo = User::whereId($thisDoctor->user_id)->first();
        if(!$thisUserInfo)
            return response()->json(['level' => 'error','message' => '医生不存在']);

        if(is_null($thisUserInfo->user_key) || $thisUserInfo->user_key == ''){
            $thisUserInfo->user_key = md5($thisUserInfo->password.$thisUserInfo->id.rand(1000,9999).time());
            $thisUserInfo->save();
        }

        $userMark = $thisUserInfo->user_key;

        $token = CryptoJSAES::encrypt($userMark,env('AES_KEY'));

        $cookie = Cookie::forever("user_token", $token);

        return response()->json(['level' => 'success','message' => trans("登录成功！"),'data' => $token])->withCookie($cookie);
    }

    /**
     * 修改密码
     * @param Guard $guard
     * @param Request $request
     * @return $this|\Illuminate\Http\JsonResponse
     */
    public function changePassword(Guard $guard,Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $oldPassword = $request->get('oldpassword');
        $newpassword = $request->get('newpassword');
        $repass   = $request->get('repass');


        if(is_null($oldPassword) && $oldPassword == '')
            return response()->json(['level' => 'error','message' => '请输入原密码']);

        if(is_null($newpassword) && $newpassword == '')
            return response()->json(['level' => 'error','message' => '请输入新密码']);

        if(is_null($repass) && $repass == '')
            return response()->json(['level' => 'error','message' => '请再次输入新密码']);

        if(!Hash::check($oldPassword,$adminUser->password))
            return response()->json(['level'=>'error','message'=>'原密码不匹配！']);

        if(Hash::check($newpassword,$adminUser->password))
            return response()->json(['level'=>'error','message'=>'原密码与新密码不能一致！']);

        if($newpassword != $repass)
            return response()->json(['level'=>'error','message' => '两次密码不一致！']);

        $adminUser->password = bcrypt($newpassword);
        $adminUser->save();

        $loginOut = Cookie::forget('user_token');

        return response()->json(['level'=>'success','message'=>trans("密码修改成功！"),'data' => 'no_login'])->withCookie($loginOut);
    }

    /**
     * 退出登录
     * @param Request $request
     * @return $this
     */
    public function loginOut(Request $request){
        $cookie = Cookie::forget('user_token');

        return response()->json(['level' => 'success','message' => '退出成功','data' => 'no_login'])->withCookie($cookie);
    }

    /**
     * 获取管理员用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAdminUserInfo(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        /** @var Doctors $doctor */
        $doctor = Doctors::whereUserId($adminUser->id)->first();
        if($doctor){
            if(!is_null($doctor->doc_name) && $doctor->doc_name != ''){
                $adminUser->username =  $doctor->doc_name;
            }else{
                /** @var UserInfo $userInfo */
                $userInfo = UserInfo::whereUserId($adminUser->id)->first();
                if($userInfo){
                    if(!is_null($userInfo->nick) && $userInfo->nick != ''){
                        $adminUser->username =  $userInfo->nick;
                    }else{
                        $adminUser->username =  '';
                    }
                }
            }
        }else{
            /** @var UserInfo $userInfo */
            $userInfo = UserInfo::whereUserId($adminUser->id)->first();
            if($userInfo){
                if(!is_null($userInfo->nick) && $userInfo->nick != ''){
                    $adminUser->username =  $userInfo->nick;
                }else{
                    $adminUser->username =  '';
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $adminUser]);
    }

    /**
     * 获取管理员列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function adminList(Request $request){
//        /** @var User $adminUser */
//        $adminUser = UserManager::isLogin($request,$front = 1);
//        if(!$adminUser)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page    = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit   = !is_null($request->get('limit')) ? $request->get('limit') : 16;

        $arr = [
            'page' => $page,
            'limit' => $limit,
        ];

        $adminUserList = User::whereRole(1)->orderBy('created_at','desc')->get();
        if(count($adminUserList) > 0){
            foreach($adminUserList as $adminUser){
                $UserRole = DB::table('role_user')->where('user_id',$adminUser->id)->first();
                if($UserRole){
                    /** @var Role $role */
                    $role = Role::whereId($UserRole->role_id)->first();
                    if($role){
                        $adminUser->role_name = $role->display_name;
                    }else{
                        $adminUser->role_name = null;
                    }
                }else{
                    $adminUser->role_name = null;
                }
            }
        }

        $arr['total'] = count($adminUserList);

        $start = ($page - 1) * $limit;
        if($adminUserList)
            $adminUserList = array_slice($adminUserList->toArray(), $start, $limit);//分页显示

        return response()->json(['level' => 'success','message' => '获取成功','data' => $adminUserList,'page_info' => $arr]);
    }

    /**
     * 编辑管理员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function adminSet(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thisAdminUser = User::whereRole(1)->whereId($id)->first();
        if($thisAdminUser){
            $roleUsers = DB::table('role_user')->where('user_id',$thisAdminUser->id)->get();
            $roleIds = array();
            if(count($roleUsers) > 0){
                foreach($roleUsers as $roleUser){
                    /** @var Role $role */
                    $roleList = Role::whereId($roleUser->role_id)->get();
                    if(count($roleList) > 0){
                        foreach($roleList as $role){
                            $roleObj = (object)['id' => $role->id,'role' => $role->display_name];
                            array_push($roleIds,$roleObj);
                        }
                    }

                }
            }

            $thisAdminUser->role_id_list = $roleIds;
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $thisAdminUser,'id' => $id]);
    }

    /**
     * 添加管理员用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setAdmin(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $username = $request->get('username');
        $password = $request->get('password');
        $roleIds  = $request->get('role_id');
        $repass   = $request->get('repass');
        $status   = !is_null($request->get('status')) && $request->get('status') != '' ? $request->get('status') : 0;
        $id       = !is_null($request->get('id')) ? $request->get('id') : 0;

        if(is_null($password) && $password == '')
            return response()->json(['level' => 'error','message' => '请输入密码']);

        if(is_null($repass) && $repass == '')
            return response()->json(['level' => 'error','message' => '请再次输入密码']);

        if($password != $repass)
            return response()->json(['level'=>'error','message' => '两次密码不一致！']);

        /** @var User $hasUser */
        $hasUser = User::whereUsername(trim($username))->first();

        /** @var User $thatUser */
        $thatUser = User::whereId($id)->first();

        if($thatUser && ($hasUser && $thatUser->id != $hasUser->id))
            return response()->json(['level' => 'error','message' => '当前管理员账号已存在']);

        if(!$thatUser){
            if($hasUser)
                return response()->json(['level'=>'error','message' => '当前管理员账号已存在']);

            $thatUser = new User();
        }

        $thatUser->username = $username;
        $thatUser->password = bcrypt($password);
        $thatUser->user_key = md5($password . $adminUser->id . rand(1000,9999).time());
        $thatUser->role     = 1;
        $thatUser->status   = $status;
        $thatUser->save();

        DB::table('role_user')->where('user_id',$thatUser->id)->delete();

        if(is_array($roleIds)){
            if(count($roleIds) > 0){
                foreach($roleIds as $roleId){
                    DB::table('role_user')->insert(['user_id' => $thatUser->id,'role_id' => $roleId]);
                }
            }
        }else{
            return response()->json(['level' => 'error','message' => '角色的数据格式不对']);
        }

        return response()->json(['level'=>'success','message'=>'添加成功','data'=>$thatUser]);
    }

    /**
     * 删除管理员用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delAdmin(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var User $thatUser */
        $thatUser = User::whereId($id)->first();

        if(!$thatUser)
            return response()->json(["level"=>"error","message"=>"该管理员不存在！"]);

        $thatUser->forceDelete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatUser]);
    }

    /**
     * 获取角色列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function roleList(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page    = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit   = !is_null($request->get('limit')) ? $request->get('limit') : 16;

        $arr = [
            'page' => $page,
            'limit' => $limit,
        ];

        $roles = Role::orderBy('created_at','desc')->get();

        $arr['total'] = count($roles);

        $start = ($page - 1) * $limit;
        if($roles)
            $roles = array_slice($roles->toArray(), $start, $limit);//分页显示

        return response()->json(['level' => 'success','message' => '获取成功','data' => $roles,'page_info' => $arr]);
    }

    /**
     * 编辑角色
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function roleSet(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var Role $role */
        $role = Role::whereId($id)->first();
        if($role){
            $permissionRoles = DB::table('permission_role')->where('role_id',$role->id)->get();
            $permissionIds = array();
            if(count($permissionRoles) > 0){
                foreach($permissionRoles as $permissionRole){
                    /** @var Permission $permission */
                    $permissionList = Permission::whereId($permissionRole->permission_id)->get();
                    if(count($permissionList) > 0){
                        foreach($permissionList as $permission){
                            $permissionObj = (object)['id' => $permission->id,'permission' => $permission->display_name];
                            array_push($permissionIds,$permissionObj);
                        }
                    }

                }
            }

            $role->permission_id_list = $permissionIds;
        }

        /** @var Permission $permission */
        $permissions = Permission::all();
        $permissionArr = array();
        if(count($permissions) > 0){
            foreach($permissions as $permission){
                $permissionInfo = (object)['id' => $permission->id,'permission' => $permission->display_name];
                array_push($permissionArr,$permissionInfo);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $role,'permission_list' => $permissionArr]);
    }

    /**
     * 添加角色
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setRole(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $name          = $request->get('name');
        $displayName   = $request->get('display_name');
        $description   = $request->get('description');
        $id            = !is_null($request->get('id')) ? $request->get('id') : 0;
        $permissionIds = $request->get('permission_ids');

        $newRole = Role::whereId($id)->first();
        if(!$newRole)
            $newRole = new Role();

        if(!is_null($name))$newRole->name = $name;
        if(!is_null($displayName))$newRole->display_name = $displayName;
        if(!is_null($description))$newRole->description = $description;
        $newRole->save();

        DB::table('permission_role')->where('role_id',$newRole->id)->delete();

        if(is_array($permissionIds)){
            if(count($permissionIds) > 0){
                foreach($permissionIds as $permissionId){
                    DB::table('permission_role')->insert(['role_id' => $newRole->id,'permission_id' => $permissionId]);
                }
            }
        }else{
            return response()->json(['level' => 'error','message' => '权限的数据格式不对']);
        }

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newRole]);
    }

    /**
     * 删除角色
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delRole(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thisRole = Role::whereId($id)->first();
        if(!$thisRole)
            return response()->json(['level' => 'error','message' => '该角色不存在']);

        $thisRole = DB::table('roles')->where('id',$id)->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thisRole]);
    }

    /**
     * 获取权限列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function permissionsList(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page    = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit   = !is_null($request->get('limit')) ? $request->get('limit') : 16;

        $arr = [
            'page' => $page,
            'limit' => $limit,
        ];

        $permissions = Permission::orderBy('created_at','desc')->get();

        $arr['total'] = count($permissions);

        $start = ($page - 1) * $limit;
        if($permissions)
            $permissions = array_slice($permissions->toArray(), $start, $limit);//分页显示

        return response()->json(['level' => 'success','message' => '获取成功','data' => $permissions,'page_info' => $arr]);
    }

    /**
     * 编辑权限
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function permissionsSet(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

//        $id = !is_null($request->get('id')) ? $request->get('id') : 0;
        $id = $request->get('id');


        $permission = Permission::whereId($id)->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $permission,'id' => $id]);
    }

    /**
     * 添加权限
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setPermissions(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $name          = $request->get('name');
        $displayName   = $request->get('display_name');
        $description   = $request->get('description');
        $id            = !is_null($request->get('id')) ? $request->get('id') : 0;

        $newPermission = Permission::whereId($id)->first();
        if(!$newPermission)
            $newPermission = new Permission();

        if(!is_null($name))$newPermission->name = $name;
        if(!is_null($displayName))$newPermission->display_name = $displayName;
        if(!is_null($description))$newPermission->description = $description;
        $newPermission->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newPermission]);
    }

    /**
     * 删除权限
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delPermissions(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thisPermission = Permission::whereId($id)->first();
        if(!$thisPermission)
            return response()->json(['level' => 'error','message' => '该角色不存在']);

        $thisPermission = DB::table('permissions')->where('id',$id)->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thisPermission]);
    }

    /**
     * banner列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bannerList(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page    = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit   = !is_null($request->get('limit')) ? $request->get('limit') : 16;

        $arr = [
            'page' => $page,
            'limit' => $limit,
        ];

        /** @var Banner $sysBanner */
        $sysBanners = Banner::orderBy('sort','asc')->orderBy('created_at','desc')->get();
        if(count($sysBanners) > 0){
            foreach($sysBanners as $sysBanner){
                $sysBanner->img_url = FileManager::getImgUrl($sysBanner->img_id);
            }
        }

        $arr['total'] = count($sysBanners);

        $start = ($page - 1) * $limit;
        if($sysBanners)
            $sysBanners = array_slice($sysBanners->toArray(), $start, $limit);//分页显示

        return response()->json(['level' => 'success','message' => '获取成功','data' => $sysBanners,'page_info' => $arr]);
    }

    /**
     * banner信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bannerSet(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var Banner $thatBanner */
        $thatBanner = Banner::whereId($id)->first();
        if($thatBanner){
            $thatBanner->img_url = FileManager::getImgUrl($thatBanner->img_id);
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $thatBanner]);
    }

    /**
     * 设置banner
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setBanner(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $title   = $request->get('title');
        $linkUrl = $request->get('link_url');
        $sort    = $request->get('sort');
        $imgId   = $request->get('img_id');
        $id      = !is_null($request->get('id'))?$request->get('id'):0;

        $thatBanner = Banner::whereId(trim($id))->first();

        if(!$thatBanner)
            $thatBanner = new Banner();

        if(!is_null($title))$thatBanner->title = $title;
        if(!is_null($linkUrl))$thatBanner->link_url = $linkUrl;
        if(!is_null($sort))$thatBanner->sort = $sort;
        if(!is_null($imgId))$thatBanner->img_id = $imgId;
        $thatBanner->save();

        return response()->json(["level"=>"success","message"=>"添加或修改成功","data"=>$thatBanner]);
    }

    /**
     * 删除banner
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delBanner(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var Banner $thatBanner */
        $thatBanner = Banner::whereId($id)->first();

        if(!$thatBanner)
            return response()->json(["level"=>"error","message"=>"该banner不存在！"]);

        $thatBanner->delete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatBanner]);
    }

    /**
     * 统计
     * @param Request $request
     */
    public function dataCount(Request $request){
//        /** @var User $adminUser */
//        $adminUser = UserManager::isLogin($request,$front = 1);
//        if(!$adminUser)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        //每日的年月日
        $todayY = date("Y",time());
        $todayM = date("m",time());
        $todayD = date("d",time());

        ///每日的开始时间和结束时间
        $todayStartTime = mktime(0,0,0,$todayM,$todayD,$todayY);
        $todayEndTime   = mkTime(23,59,59,$todayM,$todayD,$todayY);

        //每日前一天的开始时间和结束时间
        $toOneStartTime = mktime(0,0,0,$todayM,$todayD - 1,$todayY);
        $toOneEndTime   = mkTime(23,59,59,$todayM,$todayD - 1,$todayY);

        //每日前两天的开始时间和结束时间
        $toTwoStartTime = mktime(0,0,0,$todayM,$todayD - 2,$todayY);
        $toTwoEndTime   = mkTime(23,59,59,$todayM,$todayD - 2,$todayY);

        //每日前三天的开始时间和结束时间
        $toThreeStartTime = mktime(0,0,0,$todayM,$todayD - 3,$todayY);
        $toThreeEndTime   = mkTime(23,59,59,$todayM,$todayD - 3,$todayY);

        //每日前四天的开始时间和结束时间
        $toFourStartTime = mktime(0,0,0,$todayM,$todayD - 4,$todayY);
        $toFourEndTime   = mkTime(23,59,59,$todayM,$todayD - 4,$todayY);

        //每日前五天的开始时间和结束时间
        $toFiveStartTime = mktime(0,0,0,$todayM,$todayD - 5,$todayY);
        $toFiveEndTime   = mkTime(23,59,59,$todayM,$todayD - 5,$todayY);

        //每日前六天的开始时间和结束时间
        $toSixStartTime = mktime(0,0,0,$todayM,$todayD - 6,$todayY);
        $toSixEndTime   = mkTime(23,59,59,$todayM,$todayD - 6,$todayY);

        //存放结果
        $result = [];

        //前六天的登录记录
        $toSixLoginRecord = EveryDayLoginRecord::whereBetween('login_time',[date("Y-m-d H:i:s",$toSixStartTime),date("Y-m-d H:i:s",$toSixEndTime)])->lists('user_id')->toArray();

        $toSixUserIds = array_unique($toSixLoginRecord);

        $toSixUserCount = count($toSixUserIds);

        $toSixTime = date("m",$toSixStartTime) . '月' . date("d",$toSixStartTime) . '日';

        $result['user_login']['one_day']['time'] = $toSixTime;
        $result['user_login']['one_day']['login_count'] = $toSixUserCount;

        //前五天的登录记录
        $toFiveLoginRecord = EveryDayLoginRecord::whereBetween('login_time',[date("Y-m-d H:i:s",$toFiveStartTime),date("Y-m-d H:i:s",$toFiveEndTime)])->lists('user_id')->toArray();

        $toFiveUserIds = array_unique($toFiveLoginRecord);

        $toFiveUserCount = count($toFiveUserIds);

        $toFiveTime = date("m",$toFiveStartTime) . '月' . date("d",$toFiveStartTime) . '日';

        $result['user_login']['two_day']['time'] = $toFiveTime;
        $result['user_login']['two_day']['login_count'] = $toFiveUserCount;

        //前四天的登录记录
        $toFourLoginRecord = EveryDayLoginRecord::whereBetween('login_time',[date("Y-m-d H:i:s",$toFourStartTime),date("Y-m-d H:i:s",$toFourEndTime)])->lists('user_id')->toArray();

        $toFourUserIds = array_unique($toFourLoginRecord);

        $toFourUserCount = count($toFourUserIds);

        $toFourTime = date("m",$toFourStartTime) . '月' . date("d",$toFourStartTime) . '日';

        $result['user_login']['three_day']['time'] = $toFourTime;
        $result['user_login']['three_day']['login_count'] = $toFourUserCount;

        //前三天的登录记录
        $toThreeLoginRecord = EveryDayLoginRecord::whereBetween('login_time',[date("Y-m-d H:i:s",$toThreeStartTime),date("Y-m-d H:i:s",$toThreeEndTime)])->lists('user_id')->toArray();

        $toThreeUserIds = array_unique($toThreeLoginRecord);

        $toThreeUserCount = count($toThreeUserIds);

        $toThreeTime = date("m",$toThreeStartTime) . '月' . date("d",$toThreeStartTime) . '日';

        $result['user_login']['four_day']['time'] = $toThreeTime;
        $result['user_login']['four_day']['login_count'] = $toThreeUserCount;

        //前二天的登录记录
        $toTwoLoginRecord = EveryDayLoginRecord::whereBetween('login_time',[date("Y-m-d H:i:s",$toTwoStartTime),date("Y-m-d H:i:s",$toTwoEndTime)])->lists('user_id')->toArray();

        $toTwoUserIds = array_unique($toTwoLoginRecord);

        $toTwoUserCount = count($toTwoUserIds);

        $toTwoTime = date("m",$toTwoStartTime) . '月' . date("d",$toTwoStartTime) . '日';

        $result['user_login']['five_day']['time'] = $toTwoTime;
        $result['user_login']['five_day']['login_count'] = $toTwoUserCount;

        //前一天的登录记录
        $toOneLoginRecord = EveryDayLoginRecord::whereBetween('login_time',[date("Y-m-d H:i:s",$toOneStartTime),date("Y-m-d H:i:s",$toOneEndTime)])->lists('user_id')->toArray();

        $toOneUserIds = array_unique($toOneLoginRecord);

        $toOneUserCount = count($toOneUserIds);

        $toOneTime = date("m",$toOneStartTime) . '月' . date("d",$toOneStartTime) . '日';

        $result['user_login']['six_day']['time'] = $toOneTime;
        $result['user_login']['six_day']['login_count'] = $toOneUserCount;

        //当天的登录记录
        $todayLoginRecord = EveryDayLoginRecord::whereBetween('login_time',[date("Y-m-d H:i:s",$todayStartTime),date("Y-m-d H:i:s",$todayEndTime)])->lists('user_id')->toArray();

        $todayUserIds = array_unique($todayLoginRecord);

        $todayUserCount = count($todayUserIds);

        $todayTime = date("m",$todayStartTime) . '月' . date("d",$todayStartTime) . '日';

        $result['user_login']['seven_day']['time'] = $todayTime;
        $result['user_login']['seven_day']['login_count'] = $todayUserCount;


        $result['integral_rank'] = array();
        //积分榜前十名
        /** @var VipInfo $integralRank */
        $integralRankList = VipInfo::whereIsVip(1)->whereStatus(1)->where('end_time' , '>' , date('Y-m-d H:i:s',time()))->orderBy('integral','desc')->take(10)->get();
        if(count($integralRankList) > 0){
            foreach($integralRankList as $integralRank){
                $real_name = '';

                if(!is_null($integralRank->realname) && $integralRank->realname != ''){
                    $real_name = $integralRank->realname;
                }else{
                    /** @var UserInfo $userInfo */
                    $userInfo = UserInfo::whereId($integralRank->user_id)->first();
                    if($userInfo){
                        if(!is_null($userInfo->nickname) && $userInfo->nickname != ''){
                            $real_name = $userInfo->nickname;
                        }
                    }
                }

                $data = (object)['real_name' => $real_name,'integral' => $integralRank->integral];

                array_push($result['integral_rank'],$data);
            }
        }

        //普通用户和会员用户比率
        //总用户数量
        $user = User::count();
        //会员用户
        $userVIp = VipInfo::whereIsVip(1)->whereStatus(1)->where('end_time','>',date('Y-m-d H:i:s',time()))->count();

        //百分比
        $userRatio = round(($user - $userVIp) / $user * 100,2) . "%";
        $vipRatio  = round(($userVIp / $user) * 100,2) . '%';

        $result['user_ratio']['user'] = $user;
        $result['user_ratio']['vip_user'] = $userVIp;

        return response()->json(['level' => 'success','message' => '获取成功','data' => $result]);
    }

    /**
     * 获取功能模块列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getFeaturesMenu(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page    = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit   = !is_null($request->get('limit')) ? $request->get('limit') : 16;

        $arr = [
            'page' => $page,
            'limit' => $limit,
        ];
        /** @var FeaturesMenu $featuresMenu */
        $featuresMenuList = FeaturesMenu::orderBy('sort','asc')->orderBy('created_at','desc')->get();
        if(count($featuresMenuList) > 0){
            foreach($featuresMenuList as $featuresMenu){
                $featuresMenu->img_url = FileManager::getImgUrl($featuresMenu->img_id);
            }
        }

        $arr['total'] = count($featuresMenuList);

        $start = ($page - 1) * $limit;
        if($featuresMenuList)
            $featuresMenuList = array_slice($featuresMenuList->toArray(), $start, $limit);//分页显示


        return response()->json(['level' => 'success','message' => '获取成功','data' => $featuresMenuList,'page_info' => $arr]);
    }

    /**
     * 获取功能模块详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function featuresMenuDetail(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var FeaturesMenu $featuresMenu */
        $featuresMenu = FeaturesMenu::whereId($id)->first();
        if($featuresMenu){
            $featuresMenu->img_url = FileManager::getImgUrl($featuresMenu->img_id);
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $featuresMenu]);
    }

    /**
     * 设置功能模块
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setFeaturesMenu(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $title   = !is_null($request->get('title')) ? $request->get('title') : '';
        $imgId   = !is_null($request->get('img_id')) ? $request->get('img_id') : 0;
        $linkUrl = !is_null($request->get('link_url')) ? $request->get('link_url') : '';
        $appId   = !is_null($request->get('appid')) ? $request->get('appid') : '';
        $sort    = !is_null($request->get('sort')) ? $request->get('sort') : 0;
        $status  = !is_null($request->get('status')) ? $request->get('status') : 0;
        $id      = !is_null($request->get('id')) ? $request->get('id') : 0;

        $newFeaturesMenu = FeaturesMenu::whereId($id)->first();
        if(!$newFeaturesMenu)
            $newFeaturesMenu = new FeaturesMenu();

        if($imgId != '')$newFeaturesMenu->img_id                   = $imgId;
        if($title != '')$newFeaturesMenu->title                    = $title;
        if($linkUrl != '')$newFeaturesMenu->link_url               = $linkUrl;
        if($appId != '')$newFeaturesMenu->appid                    = $appId;
        if($sort != '')$newFeaturesMenu->sort                      = $sort;
        if($status != '')$newFeaturesMenu->status                  = $status;
        $newFeaturesMenu->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newFeaturesMenu]);
    }

    /**
     * 删除功能模块接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delFeaturesMenu(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thatFeaturesMenu = FeaturesMenu::whereId($id)->first();
        if(!$thatFeaturesMenu)
            return response()->json(['level' => 'error','message' => '这条数据不存在']);

        $thatFeaturesMenu->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thatFeaturesMenu]);
    }

    /**
     * 获取会员规则列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getVipRuleList(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page    = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit   = !is_null($request->get('limit')) ? $request->get('limit') : 16;

        $arr = [
            'page' => $page,
            'limit' => $limit,
        ];

        $vipRuleList = VipRule::orderBy('sort','asc')->orderBy('created_at','desc')->get();

        $arr['total'] = count($vipRuleList);

        $start = ($page - 1) * $limit;
        if($vipRuleList)
            $vipRuleList = array_slice($vipRuleList->toArray(), $start, $limit);//分页显示

        return response()->json(['level' => 'success','message' => '获取成功','data' => $vipRuleList,'page_info' => $arr]);
    }

    /**
     * 获取会员详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getVipRuleDetail(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $vipRule = VipRule::whereId($id)->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $vipRule]);
    }

    /**
     * 设置会员规则
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setVipRule(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $name          = !is_null($request->get('name')) ? $request->get('name') : '';
        $level         = !is_null($request->get('level')) ? $request->get('level') : 1;
        $prefix        = !is_null($request->get('prefix')) ? $request->get('prefix') : '';
        $effectiveTime = !is_null($request->get('effective_time')) ? $request->get('effective_time') : 1;
        $numberLimit   = !is_null($request->get('number_limit')) ? $request->get('number_limit') : 1;
        $costStandard  = !is_null($request->get('cost_standard')) ? $request->get('cost_standard') : '';
        $sort          = !is_null($request->get('sort')) ? $request->get('sort') : 0;
        $remark        = !is_null($request->get('remark')) ? $request->get('remark') : '';
        $id            = !is_null($request->get('id')) ? $request->get('id') : 0;

        if($level < 0)
            return response()->json(['level' => 'error','message' => '请输入正整数']);

        $newVipRule = VipRule::whereId($id)->first();
        if(!$newVipRule)
            $newVipRule = new VipRule();

        if($name != '')$newVipRule->name                                             = $name;
        if($level != '' && $level != 0)$newVipRule->level                            = $level;
        if($prefix != '')$newVipRule->prefix                                         = $prefix;
        if($effectiveTime != '' && $effectiveTime != 0)$newVipRule->effective_time   = $effectiveTime;
        if($numberLimit != '' && $numberLimit != 0)$newVipRule->number_limit         = $numberLimit;
        if($costStandard != '' && $costStandard != 0)$newVipRule->cost_standard      = $costStandard;
        $newVipRule->remark                                                          = $remark;
        if($sort != '' && $sort != 0)$newVipRule->sort                               = $sort;
        $newVipRule->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newVipRule]);
    }

    /**
     * 删除会员规则
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delVipRule(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var VipRule $thatVipRule */
        $thatVipRule = VipRule::whereId($id)->first();
        if(!$thatVipRule)
            return response()->json(['level' => 'error','message' => '该数据不存在']);

        $isPayRule = PayRule::whereVipRuleId($thatVipRule->id)->count();
        if($isPayRule > 0)
            return response()->json(['level' => 'error','message' => '该规则下还有付费方式，不能删除']);

        $thatVipRule->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thatVipRule]);
    }

    /**
     * 获取收款方式列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getPayRuleList(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page    = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit   = !is_null($request->get('limit')) ? $request->get('limit') : 16;

        $arr = [
            'page' => $page,
            'limit' => $limit,
        ];

        $vipRuleId = !is_null($request->get('vip_rule_id')) ? $request->get('vip_rule_id') : 0;

        /** @var PayRule $payRule */
        $payRuleList = PayRule::whereVipRuleId($vipRuleId)->orderBy('sort','asc')->orderBy('created_at','desc')->get();
        if(count($payRuleList) > 0){
            foreach($payRuleList as $payRule){
                /** @var VipRule $vipRule */
                $vipRule = VipRule::whereId($payRule->vip_rule_id)->first();
                if($vipRule){
                    $payRule->vip_rule_name = $vipRule->name;
                }else{
                    $payRule->vip_rule_name = '';
                }

                if($payRule->type == 0){
                    $payRule->type_name = '免费';
                }elseif($payRule->type == 1){
                    $payRule->type_name = '一次性';
                }elseif($payRule->type == 2){
                    $payRule->type_name = '分期';
                }else{
                    $payRule->type_name = '未知';
                }

                if($payRule->is_retreat == 1){
                    $payRule->is_retreat_name = '可返还';
                }else{
                    $payRule->is_retreat_name = '不可返还';
                }
            }
        }

        $arr['total'] = count($payRuleList);

        $start = ($page - 1) * $limit;
        if($payRuleList)
            $payRuleList = array_slice($payRuleList->toArray(), $start, $limit);//分页显示

        return response()->json(['level' => 'success','message' => '获取成功','data' => $payRuleList,'page_info' => $payRuleList]);
    }

    /**
     * 获取收款方式详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getPayRuleDetail(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var PayRule $payRule */
        $payRule = PayRule::whereId($id)->first();
        if($payRule){
            /** @var VipRule $vipRule */
            $vipRule = VipRule::whereId($payRule->vip_rule_id)->first();
            if($vipRule){
                $payRule->vip_rule_name = $vipRule->name;
            }else{
                $payRule->vip_rule_name = '';
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $payRule]);
    }

    /**
     * 设置付费方式
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setPayRule(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $vipRuleId       = !is_null($request->get('vip_rule_id')) ? $request->get('vip_rule_id') : 0;
        $basicPrice      = !is_null($request->get('basic_price'))  && $request->get('basic_price') != '' ? $request->get('basic_price') : 0.00;
        $vipGradePrice   = !is_null($request->get('vip_grade_price'))  && $request->get('vip_grade_price') != '' ? $request->get('vip_grade_price') : 0.00;
        $type            = !is_null($request->get('type'))  && $request->get('type') != '' ? $request->get('type') : 1;
        $isRetreat       = !is_null($request->get('is_retreat'))  && $request->get('is_retreat') != '' ? $request->get('is_retreat') : 0;
        $sort            = !is_null($request->get('sort')) && $request->get('sort') != '' ? $request->get('sort') : 0;
        $remark          = !is_null($request->get('remark')) ? $request->get('remark') : '';
        $id              = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var VipRule $thisVipRule */
        $thisVipRule = VipRule::whereId($vipRuleId)->first();
        if(!$thisVipRule)
            return response()->json(['level' => 'error','message' => '会员规则不存在']);

        /** @var PayRule $isTypeRepeat */
        $isTypeRepeat = PayRule::whereType($type)->whereVipRuleId($thisVipRule->id)->first();

        /** @var PayRule $newPayRule */
        $newPayRule = PayRule::whereId($id)->first();

        if($isTypeRepeat && ($newPayRule && $newPayRule->id != $isTypeRepeat->id))
            return response()->json(['level' => 'error','message' => '该规则已存在']);

        if(!$newPayRule){
            if($isTypeRepeat)
                return response()->json(['level' => 'error','message' => '该规则已存在']);

            $newPayRule = new PayRule();
        }

        $newPayRule->vip_rule_id              = $thisVipRule->id;
        $newPayRule->basic_price              = $basicPrice;
        $newPayRule->vip_grade_price          = $vipGradePrice;
        $newPayRule->type                     = $type;
        $newPayRule->is_retreat               = $isRetreat;
        $newPayRule->remark                   = $remark;
        $newPayRule->sort                     = $sort;
        $newPayRule->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newPayRule]);
    }

    /**
     * 删除付费方式
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delPayRule(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thatPayRule = PayRule::whereId($id)->first();
        if(!$thatPayRule)
            return response()->json(['level' => 'error','message' => '付费方式不存在']);

        $thatPayRule->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thatPayRule]);
    }

    /**
     * 获取积分规则列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getIntegralRuleList(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page = $request->has('page')?$request->input('page'):1;
        $pagesize = $request->has('pagesize')?$request->input('pagesize'):16;
        $type     = !is_null($request->get('type')) ? $request->get('type') : '';

        $arr = [
            'page'=>$page,
            'pagesize'=>$pagesize,
        ];

        /** @var IntegralRule $integralRule */
        if($type != ''){
            $integralRuleList = IntegralRule::whereType($type)->orderBy('created_at')->get();
        }else{
            $integralRuleList = IntegralRule::orderBy('created_at')->get();
        }
        if(count($integralRuleList) > 0){
            foreach($integralRuleList as $integralRule){
                if($integralRule->type == 'activity'){
                    $integralRule->type_name = '活动';
                }elseif($integralRule->type == 'donate'){
                    $integralRule->type_name = '捐赠';
                }elseif($integralRule->type == 'add_vip'){
                    $integralRule->type_name = '发展会员';
                }elseif($integralRule->type == 'other'){
                    $integralRule->type_name = '其他';
                }else{
                    $integralRule->type_name = '未知';
                }
            }
        }

        $arr['total'] = count($integralRuleList);

        $start = ($page - 1) * $pagesize;
        if($integralRuleList)
            $integralRuleList = array_slice($integralRuleList->toArray(), $start, $pagesize);//分页显示

        $arr['integral_rule_list'] = $integralRuleList;

        return response()->json(['level' => 'success','message' => '获取成功','data' => $integralRuleList,'page_info' => $arr]);
    }

    /**
     * 获取积分规则详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getIntegralRuleDetail(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $integralRule = IntegralRule::whereId($id)->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $integralRule]);
    }

    /**
     * 设置积分规则
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setIntegralRule(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $name            = !is_null($request->get('name')) ? $request->get('name') : '';
        $type            = !is_null($request->get('type')) ? $request->get('type') : 0;
        $num             = !is_null($request->get('num')) ? $request->get('num') : 0;
        $totalFraction   = !is_null($request->get('total_fraction')) ? $request->get('total_fraction') : 0;
        $remark          = !is_null($request->get('remark')) ? $request->get('remark') : '';
        $id              = !is_null($request->get('id')) ? $request->get('id') : 0;

        $isDonateIntegralRule = IntegralRule::whereType('donate')->first();

        $isAddVipIntegralRule = IntegralRule::whereType('add_vip')->first();

        /** @var IntegralRule $newIntegralRule */
        $newIntegralRule = IntegralRule::whereId($id)->first();

        if(!$newIntegralRule){
            if($isDonateIntegralRule)
                return response()->json(['level' => 'error','message' => '该类型的积分规则已存在']);

            if($isAddVipIntegralRule)
                return response()->json(['level' => 'error','message' => '该类型的积分规则已存在']);

            $newIntegralRule = new IntegralRule();
        }else{
            if($newIntegralRule->type == 'donate'){
                if($newIntegralRule && ($isDonateIntegralRule && $newIntegralRule->id != $isDonateIntegralRule->id))
                    return response()->json(['level' => 'error','message' => '该类型的积分规则已存在']);
            }

            if($newIntegralRule->type == 'add_vip'){
                if($newIntegralRule && ($isAddVipIntegralRule && $newIntegralRule->id != $isAddVipIntegralRule->id))
                    return response()->json(['level' => 'error','message' => '该类型的积分规则已存在']);
            }
        }

        $newIntegralRule->name             = $name;
        $newIntegralRule->type             = $type;
        $newIntegralRule->num              = $num;
        $newIntegralRule->total_fraction   = $totalFraction;
        $newIntegralRule->remark           = $remark;
        $newIntegralRule->save();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $newIntegralRule]);
    }

    /**
     * 删除积分规则
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delIntegralRule(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var IntegralRule $thatIntegralRule */
        $thatIntegralRule = IntegralRule::whereId($id)->first();
        if(!$thatIntegralRule)
            return response()->json(['level' => 'error','message' => '该数据不存在']);

        $isIntegralChildRule = IntegralChildRule::whereIntegralRuleId($thatIntegralRule->id)->count();
        if($isIntegralChildRule > 0)
            return response()->json(['level' => 'error','message' => '改规则下还有子规则，不能删除']);

        $thatIntegralRule->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thatIntegralRule]);
    }

    /**
     * 获取积分子规则列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getIntegralChildRuleList(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $integralRuleId = !is_null($request->get('integral_rule_id')) ? $request->get('integral_rule_id') : 0;
        $page    = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit   = !is_null($request->get('limit')) ? $request->get('limit') : 16;

        $arr = [
            'page' => $page,
            'limit' => $limit,
        ];

        /** @var IntegralChildRule $integralChildRule */
        $integralChildRuleList = IntegralChildRule::whereIntegralRuleId($integralRuleId)->orderBy('created_at','desc')->get();
        if(count($integralChildRuleList) > 0){
            foreach($integralChildRuleList as $integralChildRule){
                /** @var IntegralRule $integralRule */
                $integralRule = IntegralRule::whereId($integralChildRule->integral_rule_id)->first();
                if($integralRule){
                    $integralChildRule->integral_rule_name = $integralRule->name;
                }

                /** @var VipRule $vipRule */
                $vipRule = VipRule::whereId($integralChildRule->vip_rule_id)->first();
                if($vipRule){
                    $integralChildRule->vip_rule_name      = $vipRule->name;
                }
            }
        }

        $arr['total'] = count($integralChildRuleList);

        $start = ($page - 1) * $limit;
        if($integralChildRuleList)
            $integralChildRuleList = array_slice($integralChildRuleList->toArray(), $start, $limit);//分页显示


        return response()->json(['level' => 'success','message' => '获取成功','data' => $integralChildRuleList,'page_info' => $arr]);
    }

    /**
     * 获取积分子规则详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getIntegralChildRuleDetail(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var IntegralChildRule $integralChildRule */
        $integralChildRule = IntegralChildRule::whereId($id)->first();
        if($integralChildRule){
            /** @var IntegralRule $integralRule */
            $integralRule = IntegralRule::whereId($integralChildRule->integral_rule_id)->first();
            if($integralRule){
                $integralChildRule->integral_rule_name = $integralRule->name;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $integralChildRule]);
    }

    /**
     * 设置积分子规则
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setIntegralChildRule(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $integralRuleId = !is_null($request->get('integral_rule_id')) ? $request->get('integral_rule_id') : 0;
        $wordFraction   = !is_null($request->get('word_fraction')) ? $request->get('word_fraction') : 0;
        $vipRuleId      = !is_null($request->get('vip_rule_id')) ? $request->get('vip_rule_id') : 0;
        $money          = !is_null($request->get('money')) ? $request->get('money') : 0;
        $remark         = !is_null($request->get('remark')) ? $request->get('remark') : '';
        $id             = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var IntegralRule $integralRule */
        $integralRule = IntegralRule::whereId($integralRuleId)->first();
        if(!$integralRule)
            return response()->json(['level' => 'error','message' => '积分规则不存在']);

        if($wordFraction < 0)
            return response()->json(['level' => 'error','message' => '单项分不能小于0']);

        if($integralRule->type == 'add_vip'){
            /** @var VipRule $vipRule */
            $vipRule = VipRule::whereId($vipRuleId)->first();
            if(!$vipRule)
                return response()->json(['level' => 'error','message' => '会员规则不存在']);

            $newIntegralChildRule = IntegralChildRule::whereIntegralRuleId($integralRule->id)->whereVipRuleId($vipRule->id)->first();
            if(!$newIntegralChildRule)
                $newIntegralChildRule = new IntegralChildRule();

            $newIntegralChildRule->integral_rule_id     = $integralRule->id;
            $newIntegralChildRule->word_fraction        = $wordFraction;
            $newIntegralChildRule->vip_rule_id          = $vipRuleId;
            $newIntegralChildRule->remark               = $remark;
            $newIntegralChildRule->save();
        }elseif($integralRule->type == 'donate'){
            if($money < 0)
                return response()->json(['level' => 'error','message' => '价值不能小于9']);

            $newIntegralChildRule = IntegralChildRule::whereId($id)->whereIntegralRuleId($integralRule->id)->first();
            if(!$newIntegralChildRule){
                $integralChildRule = IntegralChildRule::whereIntegralRuleId($integralRule->id)->first();
                if($integralChildRule)
                    return response()->json(['level' => 'error','message' => '该规则已存在']);

                $newIntegralChildRule = new IntegralChildRule();
            }

            $newIntegralChildRule->integral_rule_id     = $integralRule->id;
            $newIntegralChildRule->word_fraction        = $wordFraction;
            $newIntegralChildRule->money                = $money;
            $newIntegralChildRule->remark               = $remark;
            $newIntegralChildRule->save();
        }else{
            $newIntegralChildRule = IntegralChildRule::whereIntegralRuleId($integralRule->id)->whereId($id)->first();
            if(!$newIntegralChildRule){
                $integralChildRule = IntegralChildRule::whereIntegralRuleId($integralRule->id)->first();
                if($integralChildRule)
                    return response()->json(['level' => 'error','message' => '该规则已存在']);

                $newIntegralChildRule = new IntegralChildRule();
            }

            $newIntegralChildRule->integral_rule_id     = $integralRule->id;
            $newIntegralChildRule->word_fraction        = $wordFraction;
            $newIntegralChildRule->remark               = $remark;
            $newIntegralChildRule->save();
        }

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newIntegralChildRule]);

    }

    /**
     * 删除积分子规则
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delIntegralChildRule(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thatIntegralChildRule = IntegralChildRule::whereId($id)->first();
        if(!$thatIntegralChildRule)
            return response()->json(['level' => 'error','message' => '该数据不存在']);

        $thatIntegralChildRule->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thatIntegralChildRule]);
    }
}
